/* eslint-disable import/no-dynamic-require */
/* eslint-disable no-shadow */
/* eslint-disable no-param-reassign */
/* eslint global-require: "error" */

// all these variations of require() are ok
import UserApi from '@/api/user';
import { setToken, getToken } from '@/utils/auth';

// const avatarUrl = require('../../assets/image/avatar.jpg');

const state = {
  token: '',
  name: getToken('userinfo') ? JSON.parse(getToken('userinfo')).name : '',
  avatar: getToken('userinfo') ? JSON.parse(getToken('userinfo')).avatar : '',
  roles: getToken('userinfo') ? JSON.parse(getToken('userinfo')).roles : '',
};
const actions = {
  // 登陆
  postLogin({ commit }, obj) {
    return new Promise((reslove, reject) => {
      UserApi.userLogin(obj).then((data) => {
        if (data.data) {
          setToken(data.data.id);
          const userInfo = {
            name: data.data.user_name,
            roles: data.data.status,
          };
          setToken(userInfo, 'userinfo');
          commit('SET_TOKEN', data.data.id);
          commit('SET_NAME', data.data.user_name);
          commit('SET_ROLES', data.data.status);
          reslove(data);
        } else {
          reject(data);
        }
      }).catch((err) => {
        reject(err);
      });
    });
  },
  // 获取用户信息
  getInfo({ commit }, id) {
    return new Promise((resolve, reject) => {
      UserApi.getUserInfo(id).then((data) => {
        if (data) {
          const obj = JSON.parse(getToken('userinfo'));

          console.log(obj);
          if (data.data) {
            obj.avatar = data.data.avatar_url;
            setToken(obj, 'userinfo');
            commit('SET_AVATAR', data.data.avatar_url);
          }
          resolve(data.data);
        } else {
          reject(data);
        }
      }).catch((err) => {
        reject(err);
      });
    });
  },
  // huoqu
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
    console.log('state.avatar=', state.avatar);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
